package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.ListPopupWindow;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteEditText;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;

public class AdminInviteActivity extends BaseActivity {

    private TextInputLayout mInputLayoutName;

    private CuteEditText mInputName;

//    private ListPopupWindow lpw;

    private TextInputLayout mInputLayoutPhone;

    private CuteEditText mInputPhone;

    private static final String[] list = new String[]{"爸爸", "妈妈", "爷爷", "奶奶", "姥爷", "姥姥"};

    private boolean isClick;

    private Baby baby;

    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        switch (reqCode) {
            case (1):
                if (resultCode == RESULT_OK) {

                    Uri contactData = data.getData();
                    Cursor c = managedQuery(contactData, null, null, null, null);
                    if (c.moveToFirst()) {


                        String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                        String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                        if (hasPhone.equalsIgnoreCase("1")) {
                            Cursor phones = getContentResolver().query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                                    null, null);
                            phones.moveToFirst();
                            String cNumber = phones.getString(phones.getColumnIndex("data1"));
                            cNumber = cNumber.replace(" ", "");
                            cNumber = cNumber.replace("-", "");
                            cNumber = cNumber.substring(cNumber.length() - 11, cNumber.length());
                            mInputPhone.setText(cNumber);
                            phones.close();
                        }
                    }
                }
                break;
            case 1000:
                if(RESULT_OK == resultCode) {
                    mInputName.setText(data.getStringExtra("relationship"));
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupLayout();
    }

    private void setupLayout() {

        baby = DatabaseManager.getInstance(this).queryBaby(mLoginInfo.getBabyID());
        if(baby == null) {
            tipShow("您已取消对该日记的关注!");
            finish();
            return;
        }

        // 初始化
        setContentView(R.layout.activity_admin_invite);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setCuteTitle(baby.getName() + "的日记邀请");
        mInputLayoutName = (TextInputLayout) findViewById(R.id.text_input_layout_name);
        mInputName = (CuteEditText) findViewById(R.id.text_input_name);
        mInputLayoutPhone = (TextInputLayout) findViewById(R.id.text_input_layout_phone);
        mInputPhone = (CuteEditText) findViewById(R.id.text_input_phone);
        CuteButton imageWeChat = (CuteButton) findViewById(R.id.image_weixin);
//        lpw = new ListPopupWindow(this);

        toolbar.setOnClickCuteToolbarListener(new CuteToolbar.OnClickCuteToolbarListener() {
            @Override
            public void onClickLeft() {
                finish();
            }

            @Override
            public void onClickRight() {

            }
        });

        // 设置
//        lpw.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
//        lpw.setAnchorView(mInputName);
//        lpw.setModal(true);
//        lpw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                String item = list[position];
//                mInputName.setText(item);
//                lpw.dismiss();
//            }
//        });


        mInputLayoutName.setHint("您正在邀请?");
        mInputName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 && s.length() <= 4) {
                    mInputLayoutName.setError(null);
                } else if (s.length() > 4) {
                    mInputLayoutName.setError("称谓不能超过4个字");
                } else {
                    mInputLayoutName.setError("请输入受邀人称谓");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mInputName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final int DRAWABLE_RIGHT = 2;

                if (event.getAction() == MotionEvent.ACTION_UP) {
//                    if (event.getRawX() >= (mInputName.getRight() - mInputName.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
//                        lpw.show();
                        Intent intent = new Intent(AdminInviteActivity.this, PetnameListActivity.class);
                        intent.putExtra("type", "relationship");
                        intent.putExtra("relationship", "爸爸");
                        intent.putExtra("title", "与宝宝的关系");
                        startActivityForResult(intent, 1000);
                        return true;
//                    }
                }
                return false;
            }
        });
        mInputName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!mInputName.hasFocus()) {
                    if (TextUtils.isEmpty(mInputName.getText())) {
                        mInputLayoutName.setError("请输入受邀人称谓");
                    }
                }
            }
        });


        mInputLayoutPhone.setHint("受邀方手机号(账号)?");
        mInputPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    mInputLayoutPhone.setError(null);
                } else {
                    mInputLayoutPhone.setError("手机格式有误");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mInputPhone.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final int DRAWABLE_RIGHT = 2;

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (event.getRawX() >= (mInputPhone.getRight() - mInputPhone.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {

                        // Create an intent to "pick" a contact, as defined by the content provider URI
                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        startActivityForResult(intent, 1);

                        return true;
                    }
                }
                return false;
            }
        });

        imageWeChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (isClick) {
                    return;
                }
                isClick = true;

                if (TextUtils.isEmpty(mInputName.getText())) {
                    tipShow("请输入受邀人称谓");
                    return;
                }

                if (TextUtils.isEmpty(mInputPhone.getText()) || mInputPhone.getText().length() < 11) {
                    tipShow("手机格式有误");
                    return;
                }

                // 网络请求
                LoginInfo loginInfo = Config.getLoginInfo(AdminInviteActivity.this);
                if (loginInfo == null) {
                    return;
                }
                String phone = loginInfo.getPhone();
                String token = loginInfo.getToken().getAccessToken();
                int babyID = loginInfo.getBabyID();
                String invitePhone = mInputPhone.getText().toString();
                String inviteName = mInputName.getText().toString();

                showProgressDialog(null, null);
                Client.requestAdminInvite(AdminInviteActivity.this, phone, token, invitePhone, babyID, inviteName, new ResponseHandler() {

                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        startActivity(value.toString());
                    }

                    @Override
                    public void onChZhRJFailure(String value) {
                        if (value.equals("该称谓已关注!")) {
                            tipShow("该称谓家人（朋友）已经关注了宝贝日记，请确认后再来邀请吧!");
                        } else if (value.equals("该手机号用户已经关注!")) {
                            tipShow("该手机号帐户已经关注了宝贝日记，请确认后再来邀请吧!");
                        } else {
                            tipShow(value);
                        }
                    }

                    @Override
                    public void onChZhRJTokenFailure(String value) {
                        tipShow(value);
                    }

                    @Override
                    public void onInnovationFinish() {
                        isClick = false;
                        dismissProgressDialog();
                    }

                    @Override
                    public void onInnovationExceptionFinish() {
                        isClick = false;
                        dismissProgressDialog();
                    }

                }, new Client.NetworkUnavailableListener() {
                    @Override
                    public void networkUnavailable() {
                        tipShow(R.string.tip_network_unavailable);
                        isClick = false;
                        dismissProgressDialog();
                    }
                });

            }
        });
    }

    private void startActivity(String msg) {
        Intent intent = new Intent(AdminInviteActivity.this, InviteShareActivity.class);
        intent.putExtra("shareMsg", msg);
        startActivity(intent);
    }

}
